import 'package:get/get.dart';
import '../model/chat_message_model.dart';
import '../data/chat_message_data.dart';

/// 聊天消息状态管理
/// 使用GetX进行全局状态管理，采用非常规命名避免标准模式
class ChatMessageState extends GetxController {
  // 所有消息
  final RxList<ChatMessageModel> _allMessages = <ChatMessageModel>[].obs;

  // 当前群聊ID
  final RxString _currentGroupId = ''.obs;

  // 当前用户ID
  final RxString _currentUserId = ''.obs;

  /// 获取所有消息
  List<ChatMessageModel> get allMessages => _allMessages.toList();

  /// 获取当前群聊ID
  String get currentGroupId => _currentGroupId.value;

  /// 获取当前用户ID
  String get currentUserId => _currentUserId.value;

  /// 设置当前群聊ID
  void setCurrentGroupId(String groupId) {
    _currentGroupId.value = groupId;
  }

  /// 设置当前用户ID
  void setCurrentUserId(String userId) {
    _currentUserId.value = userId;
  }

  /// 获取当前群聊的消息
  List<ChatMessageModel> getCurrentGroupMessages() {
    return _allMessages
        .where((message) => message.groupId == _currentGroupId.value)
        .toList()
      ..sort((a, b) => a.sendTime.compareTo(b.sendTime));
  }

  /// 获取指定群聊的消息
  List<ChatMessageModel> getGroupMessages(String groupId) {
    return _allMessages.where((message) => message.groupId == groupId).toList()
      ..sort((a, b) => a.sendTime.compareTo(b.sendTime));
  }

  /// 获取用户的所有消息
  List<ChatMessageModel> getUserMessages(String userId) {
    return _allMessages.where((message) => message.senderId == userId).toList()
      ..sort((a, b) => b.sendTime.compareTo(a.sendTime));
  }

  /// 发送消息
  void sendMessage(ChatMessageModel message) {
    if (message.isValid) {
      _allMessages.add(message);
      // 按时间排序
      _allMessages.sort((a, b) => a.sendTime.compareTo(b.sendTime));
    }
  }

  /// 发送文本消息
  void sendTextMessage(String groupId, String content) {
    final message = ChatMessageModel(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      groupId: groupId,
      senderId: _currentUserId.value,
      content: content,
      sendTime: DateTime.now(),
    );
    sendMessage(message);
  }

  /// 更新消息
  void updateMessage(ChatMessageModel updatedMessage) {
    final index = _allMessages.indexWhere(
      (message) => message.id == updatedMessage.id,
    );
    if (index != -1 && updatedMessage.isValid) {
      _allMessages[index] = updatedMessage;
      // 重新排序
      _allMessages.sort((a, b) => a.sendTime.compareTo(b.sendTime));
    }
  }

  /// 删除消息
  void deleteMessage(String messageId) {
    final index = _allMessages.indexWhere((message) => message.id == messageId);
    if (index != -1) {
      final message = _allMessages[index];
      // 只有消息发送者可以删除
      if (message.senderId == _currentUserId.value) {
        _allMessages.removeAt(index);
      }
    }
  }

  /// 根据ID获取消息
  ChatMessageModel? getMessageById(String messageId) {
    try {
      return _allMessages.firstWhere((message) => message.id == messageId);
    } catch (e) {
      return null;
    }
  }

  /// 创建新消息实例
  ChatMessageModel createNewMessage({
    required String groupId,
    required String content,
  }) {
    return ChatMessageModel(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      groupId: groupId,
      senderId: _currentUserId.value,
      content: content,
      sendTime: DateTime.now(),
    );
  }

  /// 获取消息统计信息
  Map<String, int> getMessageStatistics() {
    final stats = <String, int>{};

    // 总消息数
    stats['totalMessages'] = _allMessages.length;

    // 当前用户消息数
    stats['currentUserMessages'] =
        _allMessages
            .where((message) => message.senderId == _currentUserId.value)
            .length;

    return stats;
  }

  /// 清空所有消息
  void clearAllMessages() {
    _allMessages.clear();
  }

  /// 清空群聊消息
  void clearGroupMessages(String groupId) {
    _allMessages.removeWhere((message) => message.groupId == groupId);
  }

  @override
  void onInit() {
    super.onInit();
    _loadDefaultData();
  }

  /// 加载默认数据
  void _loadDefaultData() {
    _allMessages.assignAll(ChatMessageData.getDefaultMessages());
  }
}
